package com.edu.user.controller;

import com.edu.entity.HfdVideoInfo;
import com.edu.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Iterator;

@CrossOrigin
@RestController
@RequestMapping("manage")
public class UpLoadController {


    @RequestMapping("upload")
    public Result fileUpload(HttpServletRequest request) {
        System.out.println("文件上传");

//        使客户端浏览器，区分不同种类的数据
        ObjectMapper objectMapper = new ObjectMapper();
        String fileName = null;
        //解析请求
        String path = null;
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //List<FileItem> fileItems = servletFileUpload.parseRequest((RequestContext) request);
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                fileName = file.getOriginalFilename();
                String dirPath = "D:\\qf\\video";
                File dirFile = new File(dirPath);
                //如果目标文件夹不存在则创建目标文件夹
                if (!dirFile.exists()) {
                    dirFile.mkdir();
                }
                path = dirPath + File.separator + new Date().getTime() + "-" + fileName;
                System.out.println("path = " + path);
                //文件上传项
                BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
                int len = -1;
                byte[] bys = new byte[8192];
                while ((len = bis.read(bys)) != -1) {
                    bos.write(bys, 0, len);
                }
                bis.close();
                bos.close();
            }
            return new Result(true, 1, "成功", path);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, 1, "失败");
        }
    }


}
